package com.example.exampleproject.base;

import com.example.exampleproject.base.exception.ApiException;
import com.example.exampleproject.base.exception.BusinessException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

/**
 * 根据不同的类型发射不同的error,执行observer-->onError
 *
 */
public class HandleErrTransformer<T> implements ObservableTransformer<T, T> {
    @Override
    public ObservableSource<T> apply(@NonNull Observable<T> upstream) {
        return upstream.onErrorResumeNext(new HttpResponseFunc<>());
    }

    public static class HttpResponseFunc<T> implements Function<Throwable, Observable<T>> {
        @Override
        public Observable<T> apply(@NonNull Throwable throwable) {
            if (throwable instanceof BusinessException) {
                return Observable.error(throwable);
            } else {
                return Observable.error(ApiException.handleException(throwable));
            }
        }
    }
}
